/**
* Author: LiuJie
* Time: 2018/1/22
*/
<template>
    <div class="m-input">
        <span v-if="label" class="m-label" :style="{width:labelWidth || '80px'}">{{label}}</span>
        <input :value="value"
               :readonly="readonly"
               :disabled="disabled"
               @blur="verification($event.target.value)"
               @input="updateValue($event.target.value)"
               @focus="focus"
               :placeholder="placeholder" :type="error?'text':type"
               :style="{color:error && value?'#f56c6c':''}">
    </div>
</template>
<script>
export default {
  name: "MInput",
  props: {
    type: String,
    label: String,
    placeholder: String,
    value: String,
    disabled:{
      type:Boolean,
      default:false
    },
    readonly:{
      type:Boolean,
      default:false
    },
    required: {
      type: Boolean,
      default: false
    },
    rules: {
      type:Array,
      default:[]
    },
    labelWidth:String
  },
  data() {
    return {
      error: false
    };
  },
  methods: {
    updateValue(value) {
      this.error = false;
      this.$emit("input", value);
    },
    verification(value) {
      let rules = this.rules;
      if (this.required && value === "") {
        this.error = true;
        this.$emit("input", this.label + "不能为空");
        return;
      }
      if (rules && rules.length > 0) {
        for (let i = 0; i < rules.length; i++) {
          const item = rules[i];
          if (!item.reg.test(value)) {
            this.error = true;
            this.$emit("input", item.text);
            break;
          }
        }
      }
    },
    focus() {
      if (this.error) {
        this.$emit("input", "");
      }
    }
  },
  created() {}
};
</script>
<style scoped>
body{
  margin: 0;
}
.m-input {
  padding: 0 15px;
  background-color: white;
  text-align: left;
  display: flex;
  height: 50px;
  line-height: 50px;
  font-size: 14px;
  border-bottom: solid 1px #eee;
}
.m-input input {
  flex: 1;
  border: 0;
  font-size: inherit;
  padding: 10px 0;
  line-height: normal;
}
.m-input input:focus {
  outline: none;
}
.m-input input:not([type]):disabled{
  background:none;
}
.m-label {
  display: inline-block;
}
</style>


